import { WEBSOCKET_URL } from "@/api/constant";

class WebSocketClient {
  constructor(url) {
    this.url = url;
    this.ws = null;
    this.messageCallback = null;
    this.errorCallback = null;
    this.closeCallback = null;
  }

  connect() {
    return new Promise((resolve, reject) => {
      try {
        this.ws = uni.connectSocket({
          url: this.url,
          success: () => {
            console.log("WebSocket连接创建成功");
          },
          fail: (error) => {
            console.error("WebSocket连接创建失败:", error);
            reject(error);
          },
        });

        this.ws.onOpen(() => {
          console.log("WebSocket连接已打开");
          resolve(this.ws);
        });

        this.ws.onMessage((res) => {
          if (this.messageCallback) {
            this.messageCallback(res.data);
          }
        });

        this.ws.onError((error) => {
          console.error("WebSocket错误:", error);
          if (this.errorCallback) {
            this.errorCallback(error);
          }
        });

        this.ws.onClose(() => {
          console.log("WebSocket连接已关闭");
          if (this.closeCallback) {
            this.closeCallback();
          }
        });
      } catch (error) {
        console.error("WebSocket连接异常:", error);
        reject(error);
      }
    });
  }

  send(data) {
    if (this.ws) {
      this.ws.send({
        data: typeof data === "string" ? data : JSON.stringify(data),
      });
    }
  }

  onMessage(callback) {
    this.messageCallback = callback;
  }

  onError(callback) {
    this.errorCallback = callback;
  }

  onClose(callback) {
    this.closeCallback = callback;
  }

  close() {
    if (this.ws) {
      this.ws.close();
      this.ws = null;
    }
  }
}

// AI聊天专用的WebSocket客户端
class AIChatWebSocket extends WebSocketClient {
  constructor(baseUrl = WEBSOCKET_URL + "/ai/ws") {
    super(baseUrl);
  }

  async sendMessage(message, sessionId) {
    if (!this.ws) {
      await this.connect();
    }

    this.send({
      message,
      sessionId: sessionId || new Date().getTime().toString(),
    });
  }

  // 处理AI流式响应
  handleStreamResponse(callbacks = {}) {
    const {
      onMessage = () => {},
      onError = () => {},
      onComplete = () => {},
    } = callbacks;

    this.onMessage((data) => {
      try {
        if (data === "[DONE]") {
          onComplete();
          return;
        }
        const parsedData = JSON.parse(data);
        onMessage(parsedData);
      } catch (e) {
        console.error("解析消息错误:", e);
        onError(e);
      }
    });

    this.onError((error) => {
      console.error("AI对话错误:", error);
      onError(error);
    });
  }
}

export default AIChatWebSocket;
